#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 15 00:39:47 2018

@author: stuart
"""

from sklearn import svm
import numpy as np
import matplotlib.pyplot as pl

#随机数种子作用：种子一定时，每次生成的随机数相同
np.random.seed(0)
#随机生成两类线性可分的点 
class0_data = np.random.randn(20,2) + [2,2]
class1_data = np.random.randn(20,2) - [2,2]
data = np.vstack([class0_data,class1_data])
#前20个点的label是0，后20个点的label是1
labels = [0]*20 + [1]*20



clf = svm.SVC(kernel='linear')
clf.fit(data,labels)

#print classifier informaion
print(clf)

#print all support vectors
print(clf.support_vectors_)

#print index of all support vectors
print(clf.support_)

#print number of all support vectors for each class
print(clf.n_support_)

#predict new value
print(clf.predict([[0,0],[2,4]]))


#划分超平面的一般式方程可写成WX+b0=0，其中行向量W为(w0,w1),列向量X为(x,y)
#划分超平面的点斜式方程中斜率k= - (w0/w1),截距b= - (b0/w1)
w = clf.coef_[0]
k = - w[0]/w[1]
b0 = clf.intercept_[0]

#generate some numbers between -5 and 5
xx = np.linspace(-5,5)
yy = k * xx - b0/w[1]

#dot1 is a support vector of class0
dot1 = clf.support_vectors_[0]
yy_dowm = k * xx + (dot1[1] - k * dot1[0])

#dot2 is a support vector of class1
dot2 = clf.support_vectors_[-1]
yy_up = k * xx + (dot2[1] - k * dot2[0])

dataX = data[:,0]
dataY = data[:,1]

pl.scatter(dataX,dataY,c=labels)
pl.scatter(clf.support_vectors_[:,0],clf.support_vectors_[:,1],c='r')
pl.plot(xx,yy)
pl.plot(xx,yy_dowm,'r--')
pl.plot(xx,yy_up,'r--')
pl.show()

